import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import LayOut from "../views/layout/LayOut.vue";
import { $localStorage } from "@/utils/utils";

// 预定义的静态路由
const staticRoutes = [
  {
    path: "/",
    redirect: "/layout/home",
  },
  {
    path: "/layout",
    name: "layout",
    component: LayOut,
    children: [
      {
        path: "home",
        name: "home",
        component: HomeView,
        meta: {
          title: "home页面",
        },
      },

      // 这里将动态路由填充到 LayOut 的 children 里
    ],
  },
  {
    path: "login",
    name: "login",
    component: () => import("@/views/login/Login.vue"),
  },
  // 404 页面
  {
    path: "/:pathMatch(.*)*",
    name: "notFound",
    component: () => import("../views/NotFoundView.vue"),
  },
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: staticRoutes, // 初始使用静态路由
});

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!$localStorage.getItem("token"); // 检查是否存在 token

  // 如果目标路由不是登录页，并且没有 token，则重定向到登录页面
  if (to.name !== "login" && !isAuthenticated) {
    next({ name: "login" });
  } else {
    next(); // 继续导航
  }
});

// 动态添加路由函数
const addDynamicRoutes = (fetchedRoutes) => {
  const dynamicRoutes = fetchedRoutes.map((route) => {
    return {
      path: route.path,
      name: route.name,
      component: () => import(`@/views/${route.component}.vue`), // 根据后端返回的路径动态导入组件
      meta: {
        title: route.meta.title,
      },
    };
  });

  // 将动态路由添加到 LayOut 的 children 中
  const layoutRoute = staticRoutes.find((route) => route.name === "layout");
  if (layoutRoute) {
    layoutRoute.children.push(...dynamicRoutes);
  }

  // 重新添加动态路由到 router
  router.addRoute(layoutRoute);
};

// 假设在某个时刻获取后端路由数据
const fetchedRoutes = [
  { path: "about", name: "about", component: "AboutView", meta: { title: "about页面" } },
  { path: "map3d", name: "map3d", component: "map/index", meta: { title: "map3d页面" } },
  {
    path: "threejs",
    name: "threejs",
    component: "threeJs/threejs-test",
    meta: { title: "threejs页面" },
  },
];

// 获取后端数据后调用添加路由函数
addDynamicRoutes(fetchedRoutes);

export default router;
